//
//  NewsViewController.m
//  花花时尚
//
//  Created by 霍文轩 on 15/8/20.
//  Copyright (c) 2015年 霍文轩. All rights reserved.
//

#import "FashionViewController.h"
#import "RecommendCollectionCell.h"
#import "DressCollectionCell.h"
#import "BeautyCollectionCell.h"
#import "SportCollectionCell.h"
#import "PlayCollectionCell.h"
#import "TravelCollectionCell.h"
#import "FoodCollectionCell.h"
#import "ReadCollectionCell.h"

#import "NetWorkNotify.h"

#import "NightMode.h"
#import "GiFHUD.h"


@interface FashionViewController () <UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,RecommendCollectionCellDelegate,DressCollectionCellDelegate,BeautyCollectionCellDelegate,SportCollectionCellDelegate,PlayCollectionCellDelegate,TravelCollectionCellDelegate,FoodCollectionCellDelegate,ReadCollectionCellDelegate>
@property (nonatomic,retain) NSArray * titleButtonArray;
@property (nonatomic,assign) CGFloat directionIdentify; // 方向标识
@property (nonatomic,retain) UIVisualEffectView * visual;
@property (nonatomic,retain) UIImageView * fashionImageView;
@property (nonatomic,retain) UIView * navigationView;
@end


#define kColorValue 100
@implementation FashionViewController
//-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response{
//    
//}
//-(void)didFinishGetUMSocialDataResponse:(UMSocialResponseEntity *)response{
//    
//}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"Network" object:nil];
    [_navigationView release];
    [_fashionImageView release];
    [_visual release];
    [_titleButtonArray release];
    [_colleciton release];
    [super dealloc];
}
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if(self){
        self.directionIdentify = 0.0;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationController.navigationBar.hidden = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Network:) name:@"Network" object:nil]; // 接受消息，是否有网络连接

    
    self.navigationView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44+40)];
    
    // 添加毛玻璃
    [self addVisual];
    
    // logo
    self.fashionImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 35)];
    _fashionImageView.center = CGPointMake(self.view.frame.size.width/2, 32);
    UIImage * fashionImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NightMode nightModeON]?@"FASHION_white":@"FASHION_black" ofType:@"png"]];
    _fashionImageView.image = fashionImage;
    
    [self createCollection];
    [self.view addSubview:_navigationView]; // 在创建collection之后才能添加
    [self.view addSubview:_fashionImageView];
    
    self.titleButtonArray = @[@"推荐",@"时装",@"美容",@"运动",@"娱乐",@"旅行",@"美食",@"阅读"];
    [self createTitleButtons];
    
    [_navigationView release];
    [_fashionImageView release];
    
    [self createChildButton];
}
-(void)addVisual{
    if (_visual) {  // 因为visual创建后不能修改，所以每次修改都需要重新创建
        [_visual removeFromSuperview];
    }
    self.visual = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:[NightMode nightModeON]?UIBlurEffectStyleDark:UIBlurEffectStyleLight]];
    _visual.frame = CGRectMake(0, 0, self.view.frame.size.width, _navigationView.frame.size.height);
    [_navigationView addSubview:_visual];
    [_visual release];
}
-(void)createChildButton{
    UIButton * childButton  =[[UIButton alloc] initWithFrame:CGRectMake(15, 20, 30, 30)];
    [self.view addSubview:childButton];
    [childButton setBackgroundImage:[UIImage imageNamed:@"child.png"] forState:UIControlStateNormal];
    [childButton addTarget:self action:@selector(childButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [childButton release];
}
-(void)childButtonClick{
    [self.delegate callLeftView];    
}
-(void)createTitleButtons{
    UIButton * firstbutton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width/3.0-20, 54, self.view.frame.size.width/3.0 + 40, 30)];
    [self.view addSubview:firstbutton];
    firstbutton.tag = 1000;
    firstbutton.backgroundColor = [UIColor colorWithRed:kColorValue/255.0 green:kColorValue/255.0 blue:kColorValue/255.0 alpha:0.9];
    [firstbutton setTitle:[_titleButtonArray objectAtIndex:0] forState:UIControlStateNormal];
    [firstbutton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    firstbutton.titleLabel.font = [UIFont boldSystemFontOfSize:23];
    [firstbutton addTarget:self action:@selector(titleButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [firstbutton release];

    for(int i=7;i>0;i--){
        UIButton * button  =[[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width/3.0*2+20, 59, self.view.frame.size.width/3.0-20, 25)];
        [self.view addSubview:button];
        button.tag = 1000+i;
        [button setTitle:[_titleButtonArray objectAtIndex:i] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor colorWithRed:(kColorValue-30)/255.0 green:(kColorValue-30)/255.0 blue:(kColorValue-30)/255.0 alpha:0.9];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont boldSystemFontOfSize:18];
        [button addTarget:self action:@selector(titleButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [button release];
    }
    
}
-(void)createCollection{
    UICollectionViewFlowLayout * layout = [[[UICollectionViewFlowLayout alloc] init] autorelease];
    layout.itemSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height-49);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal; // 横屏滚动
    layout.minimumLineSpacing = 0; // 左右间隔为0
    
    self.colleciton = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-49) collectionViewLayout:layout];

    UIImage * backImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NightMode nightModeON]?@"back":@"back_null" ofType:@"png"]];
    _colleciton.backgroundColor = [UIColor colorWithPatternImage:backImage];
    _colleciton.showsHorizontalScrollIndicator = NO;
    _colleciton.bounces = NO; // 不允许回弹
    _colleciton.delegate = self;
    _colleciton.dataSource = self;
    _colleciton.pagingEnabled = YES;// 按页滚动
    _colleciton.scrollEnabled = NO; // 不允许自己滑动，需要调用touchMove滑动
    
    [_colleciton registerClass:[RecommendCollectionCell class] forCellWithReuseIdentifier:@"recommend"];
    [_colleciton registerClass:[DressCollectionCell class] forCellWithReuseIdentifier:@"dress"];
    [_colleciton registerClass:[BeautyCollectionCell class] forCellWithReuseIdentifier:@"beauty"];
    [_colleciton registerClass:[SportCollectionCell class] forCellWithReuseIdentifier:@"sport"];
    [_colleciton registerClass:[PlayCollectionCell class] forCellWithReuseIdentifier:@"play"];
    [_colleciton registerClass:[TravelCollectionCell class] forCellWithReuseIdentifier:@"travel"];
    [_colleciton registerClass:[FoodCollectionCell class] forCellWithReuseIdentifier:@"food"];
    [_colleciton registerClass:[ReadCollectionCell class] forCellWithReuseIdentifier:@"read"];
    
    // 添加横扫手势
    UISwipeGestureRecognizer * swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeActionRight)];
    [self.colleciton addGestureRecognizer:swipeRight];
    swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
    [swipeRight release];
    UISwipeGestureRecognizer * swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeActionLeft)];
    [self.colleciton addGestureRecognizer:swipeLeft];
    swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
    [swipeLeft release];
    
    [self.view addSubview:_colleciton];
    [_colleciton release];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _titleButtonArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.item) {
        case 0:{
            RecommendCollectionCell *  cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"recommend" forIndexPath:indexPath];
            cell.delegate = self;
            return cell;
        }
        case 1: {
            DressCollectionCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"dress" forIndexPath:indexPath];
            cell.delegate = self;
            return cell;
        }
        case 2:{
            BeautyCollectionCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"beauty" forIndexPath:indexPath];
            cell.delegate = self;
            return cell;
        }
        case 3:{
            SportCollectionCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"sport" forIndexPath:indexPath];
            cell.delegate = self;
            return cell;
        }
        case 4:{
            PlayCollectionCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"play" forIndexPath:indexPath];
            cell.delegate = self;
            return cell;
        }
        case 5:{
            TravelCollectionCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"travel" forIndexPath:indexPath];
            cell.delegate = self;
            return cell;
        }
        case 6:{
            FoodCollectionCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"food" forIndexPath:indexPath];
            cell.delegate = self;
            return cell;
        }
        case 7:{
            ReadCollectionCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"read" forIndexPath:indexPath];
            cell.delegate = self;
            return cell;
        }
    }
    return nil;
}

#pragma mark - UIScrollView协议，当滚动时调整titleButton字体大小，不能设置frame，有误差
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    NSInteger currentPage = scrollView.contentOffset.x/[[UIScreen mainScreen] bounds].size.width;// 每次滚完刷新当前的页数
    
    for (UIButton * button in [self.view subviews]) {
        if(button.tag == currentPage+1000){
            if(scrollView.contentOffset.x > _directionIdentify) { // 如果小于上次滚动的值，则为向左移；如果大于，就是向右移动
                // 1.将当前的titleButton变小
                button.titleLabel.font = [UIFont boldSystemFontOfSize:button.titleLabel.font.pointSize - (scrollView.contentOffset.x-_directionIdentify)/23/5];// 字体变化
                //2.将右边的button字体变大
                for (UIButton * rightButton in [self.view subviews]) {
                    if(rightButton.tag == currentPage+1000+1){
                        rightButton.titleLabel.font = [UIFont boldSystemFontOfSize:rightButton.titleLabel.font.pointSize + (scrollView.contentOffset.x-_directionIdentify)/23/5];
                    }
                }
            }
            else
                for (UIButton * button in [self.view subviews]) {
                    if(button.tag == currentPage+1000+1){
                        button.titleLabel.font = [UIFont boldSystemFontOfSize:button.titleLabel.font.pointSize + (scrollView.contentOffset.x-_directionIdentify)/23/5]; // 右移时字体变小要加，字体变大要减

                        for (UIButton * leftButton in [self.view subviews]) {
                            if(leftButton.tag == currentPage+1000){
                                leftButton.titleLabel.font = [UIFont boldSystemFontOfSize:leftButton.titleLabel.font.pointSize - (scrollView.contentOffset.x-_directionIdentify)/23/5];
                            }
                        }
                    }
                }
                
                
            
        }
    }
    self.directionIdentify = scrollView.contentOffset.x;// 每次滚动完都记录位置
}
#pragma mark - titleButton的点击
-(void)titleButtonClick:(UIButton *)button{
    NSInteger currentPage = _colleciton.contentOffset.x/self.view.frame.size.width;
    if((button.tag - 1000 - currentPage) == -1){
        [self swipeActionRight];
    }else if ((button.tag - 1000 - currentPage) == 1){
        [self swipeActionLeft];
    }
}
#pragma  mark - 禁止了scrollView的滑动，因为暴力滑动有bug，所以通过左右滑动的手势来控制collection的滑动
-(void)swipeActionRight{ // 向左滚
    NSInteger currentPage = _colleciton.contentOffset.x/[[UIScreen mainScreen] bounds].size.width; // 计算当前的页数

    // 整个collection向左滚，
    if(_colleciton.contentOffset.x>0){
        [_colleciton setContentOffset:CGPointMake(_colleciton.contentOffset.x-self.view.frame.size.width, 0) animated:YES];
        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        [self.view addSubview:view];
        [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timeFunction:) userInfo:view repeats:NO];
        
        // 如果button在中间，那么向左滚并且变小；如果在右边，那么左滚并变大
        // 字体变换
        // 背景色的透明度变换
        [UIView animateWithDuration:0.3 animations:^{
            for (UIButton * button in [self.view subviews]) {
                if(button.tag == currentPage + 1000){
                    button.frame = CGRectMake(self.view.frame.size.width/3.0*2+20, 59, self.view.frame.size.width/3.0-20, 25);
                    [button removeFromSuperview];
                    [self.view addSubview:button];
                }else if (button.tag == currentPage + 1000 - 1){
                    button.frame = CGRectMake(self.view.frame.size.width/3-20, 54, self.view.frame.size.width/3.0 + 40, 30);
                }
            }
        }];
    }
}
-(void)swipeActionLeft{ // 向右滚
    NSInteger currentPage = _colleciton.contentOffset.x/[[UIScreen mainScreen] bounds].size.width; // 计算当前的页数
    
    if(_colleciton.contentOffset.x<self.view.frame.size.width*7){
        [_colleciton setContentOffset:CGPointMake(_colleciton.contentOffset.x+self.view.frame.size.width, 0) animated:YES];
        
        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];// 用来遮盖整个屏幕，阻挡手势
        [self.view addSubview:view];
        [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timeFunction:) userInfo:view repeats:NO]; // 将view作为参数传过去。在滚的时候不允许有其他的手势操作。0.5s后把view删除
        [view release];
        
        // 如果button在中间，那么向右滚并且变小；如果在左边，右滚并变大
        [UIView animateWithDuration:0.3 animations:^{
            for (UIButton * button in [self.view subviews]) {
                if(button.tag == currentPage + 1000){
                    button.frame = CGRectMake(0, 59, self.view.frame.size.width/3.0-20, 25);
                    [button removeFromSuperview];
                    [self.view addSubview:button];
                }else if(button.tag == currentPage + 1000 + 1){
                    button.frame = CGRectMake(self.view.frame.size.width/3.0-20, 54, self.view.frame.size.width/3.0 + 40, 30);
                }
            }
        }];
    }
}

-(void)timeFunction:(NSTimer *)timer{
    [timer.userInfo removeFromSuperview];
}

#pragma mark - 滚动完成  设置按钮颜色和字体大小
-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    NSInteger currentPage = scrollView.contentOffset.x/[[UIScreen mainScreen] bounds].size.width;
    for (UIButton * button in [self.view subviews]) {
        if(button.tag == currentPage+1000){
            [UIView animateWithDuration:0.5 animations:^{
                button.backgroundColor = [UIColor colorWithRed:kColorValue/255.0 green:kColorValue/255.0 blue:kColorValue/255.0 alpha:0.9];
            }];
        }
        else if (button.tag == currentPage + 1000 - 1){
            [UIView animateWithDuration:0.5 animations:^{
                button.backgroundColor = [UIColor colorWithRed:(kColorValue-30)/255.0 green:(kColorValue-30)/255.0 blue:(kColorValue-30)/255.0 alpha:0.9];
            }];
        }
        else if (button.tag == currentPage + 1000 + 1){
            [UIView animateWithDuration:0.5 animations:^{
                button.backgroundColor = [UIColor colorWithRed:(kColorValue-30)/255.0 green:(kColorValue-30)/255.0 blue:(kColorValue-30)/255.0 alpha:0.9];
            }];
        }
    }
    // 滚动完成响应改变leftView的颜色
    [self.delegate setTextColorWithPage:currentPage];
}
-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}


#pragma mark - 为child提供滚动，根据indexPath.row来滚动
-(void)collectionScrollWithIndex:(NSInteger)index{
    _colleciton.delegate = nil; // 将scrollView的代理设置为空，防止方法内修改button的属性，didScroll同时修改
    
    NSInteger currentPage = _colleciton.contentOffset.x/[[UIScreen mainScreen] bounds].size.width; // 计算当前的页数
    // 整个collection向右滚
    if(index < currentPage){
        [_colleciton setContentOffset:CGPointMake(_colleciton.contentOffset.x-self.view.frame.size.width*(currentPage-index), 0) animated:YES];
        
        // 循环定位button的位置，和字体大小、背景颜色
        for (NSInteger i=currentPage ; i>index; i--) {
            for (UIButton * button in [self.view subviews]) {
                if(button.tag == i + 1000){
                    button.frame = CGRectMake(self.view.frame.size.width/3.0*2+20, 59, self.view.frame.size.width/3.0-20, 25);
                    button.titleLabel.font = [UIFont boldSystemFontOfSize:18];
                    button.backgroundColor = [UIColor colorWithRed:(kColorValue-30)/255.0 green:(kColorValue-30)/255.0 blue:(kColorValue-30)/255.0 alpha:0.9];
                    [self.view addSubview:button];
                }else if (button.tag == i + 1000 - 1){
                    button.frame = CGRectMake(self.view.frame.size.width/3-20, 54, self.view.frame.size.width/3.0 + 40, 30);
                    button.backgroundColor = [UIColor colorWithRed:kColorValue/255.0 green:kColorValue/255.0 blue:kColorValue/255.0 alpha:0.9];
                    button.titleLabel.font = [UIFont boldSystemFontOfSize:23];
                    [self.view addSubview:button];
                }
            }
        }
    }
    else if(index > currentPage){
        [_colleciton setContentOffset:CGPointMake(_colleciton.contentOffset.x+self.view.frame.size.width*(index-currentPage), 0) animated:YES];
        for (NSInteger i=currentPage; i<index; i++) {
            for (UIButton * button in [self.view subviews]) {
                if(button.tag == i  + 1000){
                    button.frame = CGRectMake(0, 59, self.view.frame.size.width/3.0-20, 25);
                    button.titleLabel.font = [UIFont boldSystemFontOfSize:18];
                    button.backgroundColor = [UIColor colorWithRed:(kColorValue-30)/255.0 green:(kColorValue-30)/255.0 blue:(kColorValue-30)/255.0 alpha:0.9];
                    [self.view addSubview:button];
                }else if(button.tag == i + 1000 + 1){
                    button.frame = CGRectMake(self.view.frame.size.width/3.0-20, 54, self.view.frame.size.width/3 + 40, 30);
                    button.titleLabel.font = [UIFont boldSystemFontOfSize:23];
                    button.backgroundColor = [UIColor colorWithRed:kColorValue/255.0 green:kColorValue/255.0 blue:kColorValue/255.0 alpha:0.9];
                    [self.view addSubview:button];
                }
            }
        }
    }
}
-(void)resetDelegate{
    _colleciton.delegate = self; // 当leftVC弹回去时，重新设置delegate为self，可以执行scrollView的dialing方法改变button的属性
    self.directionIdentify = _colleciton.contentOffset.x; // 重新设置滚动位置，不能在收回left之前设置，可能动画没有完成
}
#pragma mark - 接受消息通知--是否有网络
-(void)Network:(NSNotification *)notification{
    NSDictionary * dic = notification.userInfo;
    if( ! [[dic objectForKey:@"Network"] boolValue]){
        [self.view addSubview:[NetWorkNotify showNetworkNotify]];
    }
}

#pragma mark - 视图将要出现刷新视图控制器
-(void)viewDidAppear:(BOOL)animated{
    [self.view setNeedsDisplay];
    UIImage * backImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NightMode nightModeON]?@"back":@"back_null" ofType:@"png"]];
    _colleciton.backgroundColor = [UIColor colorWithPatternImage:backImage];
    UIImage * fashionImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NightMode nightModeON]?@"FASHION_white":@"FASHION_black" ofType:@"png"]];
    _fashionImageView.image = fashionImage;
    [self addVisual];
}

#pragma mark - RecommendCollectionCellDelegate 跳转分享界面
//-(void)showShareViewWithTitle:(NSString *)title image:(UIImage *)image urlString:(NSString *)urlString{
//    NSArray * snsName = [NSArray arrayWithObjects:UMShareToTencent,UMShareToWechatSession,UMShareToWechatTimeline,UMShareToWechatFavorite,UMShareToQQ,UMShareToQzone, nil];
//    
//    [UMSocialSnsService presentSnsIconSheetView:self appKey:@"55ebd5e4e0f55ad3f90017ba" shareText:title shareImage:image shareToSnsNames:snsName delegate:self];
//    
//    // 设置打开分享内容跳转链接
//    NSString * titleAndURL = [NSString stringWithFormat:@"%@\n%@",title,urlString];
//    [UMSocialData defaultData].extConfig.tencentData.title = titleAndURL; // 腾讯微博不能设置链接，只能设置title+url
//    [UMSocialData defaultData].extConfig.qqData.url = urlString;
//    [UMSocialData defaultData].extConfig.qzoneData.url = urlString;
//    [UMSocialData defaultData].extConfig.wechatFavoriteData.url = urlString;
//    [UMSocialData defaultData].extConfig.wechatSessionData.url = urlString;
//    [UMSocialData defaultData].extConfig.wechatTimelineData.url = urlString;
//}
@end
